package mspbots.data.sync.jira.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.jira.model.JiraTeam;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Iterator;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class JiraTeamReceiver extends BaseReceiver {

    @RabbitListener(queues = "jira.team.sync")
    public void process(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("jira.team.sync entry is null,or Action No Add");
            return;
        }
        Iterator<JsonNode> elements = model.getEntity().get("teams").elements();
        while (elements.hasNext()){
            JsonNode node = elements.next();
            JiraTeam data = JiraTeam.builder().otherId(node.get("id").asText()).build();
            data.setExtend(node);
            data.setTenantId(model.getTenantId());
            data.setSyncTime(LocalDateTime.now());

            this.databaseClient.execute("SELECT id FROM jira_team WHERE tenant_id =:tenantId AND other_id =:otherId")
                    .as(Long.class)
                    .bind("tenantId", data.getTenantId())
                    .bind("otherId", data.getOtherId())
                    .fetch().one()
                    .flatMap(id -> {
                        data.setId(id);
                        return this.databaseClient.update().table(JiraTeam.class).using(data).fetch().rowsUpdated();
                    })
                    .switchIfEmpty(this.databaseClient.insert().into(JiraTeam.class).using(data).fetch().rowsUpdated())
                    .subscribe(result -> log.debug("JiraTeam save is success {}", result),
                            err -> log.error("JiraTeam save or update is error,msg: {}", err.getMessage()));
        }
    }
}
